<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <a-form-item label="昵称">
              <a-input placeholder="请输入昵称" v-model="queryParam.nickname"></a-input>
            </a-form-item>
          </a-col>

          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <a-form-item label="手机号">
              <a-input placeholder="请输入手机号" v-model="queryParam.phone"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <a-form-item label="用户身份">
              <a-select v-model="queryParam.level" @change="searchQuery">
                <a-select-option v-for="(item3,index3) in levelList" :key="index3" :value="item3.level">
                  {{ item3.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :xl="12" :lg="7" :md="8" :sm="24">
            <a-form-item label="更新时间">
              <a-range-picker format="YYYY-MM-DD" :placeholder="['开始时间', '结束时间']" @change="onUpdateDateChange"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <div>
      <a-table ref="table" size="middle" :scroll="{x:true}" bordered rowKey="id" :columns="columns"
               :dataSource="dataSource" :pagination="ipagination"
               :loading="loading" class="j-table-force-nowrap" @change="handleTableChange">

        <template slot="userSlot" slot-scope="text,record">
          <div style="display:flex;align-items: center;">
            <img :src="record.headUrl" style="width:50px;height:50px;">
            <div style="padding-left:5px;">
              <div>{{ record.nickname }}</div>
              <div>{{ record.phone }}</div>
              <div>注册时间：</div>
              <div>{{ record.createTime }}</div>
            </div>
          </div>
        </template>
        <template slot="repSlot" slot-scope="text,record">
          <div>
            <span>积分：{{ record.integral }}</span>
            <a-divider type="vertical"/>
            <a @click="addIntegral(record.id)">加积分</a>
            <a-divider type="vertical"/>
            <a @click="subIntegral(record)">减积分</a>
          </div>
          <div>余额：{{ record.balance }}</div>
          <div>订单数量：{{ record.orderNum }}</div>
          <div>支付金额：{{ record.orderAmount }}</div>
        </template>

        <template slot="propSlot" slot-scope="text,record">
          <div>身份：{{ record.role == 0 ? '普通用户' : 'vip会员' }}</div>
          <div>类型：{{ (record.isCompany == 1 || record.isMember == 1) ? '企业用户' : '个人用户' }}</div>
          <div>性别：{{ record.sex_dictText }}</div>
          <div>生日：{{ record.dateBirth ? record.dateBirth : '未知' }}</div>
          <div>地区：{{ record.full_address }}</div>
        </template>

        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="55px" alt=""
               style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <!--标签和分组信息展示-->
        <template slot="crmTags" slot-scope="text,record">
          <div v-for="(item,index) in record.crmTags" :key="index" style="margin-bottom:2px;">
            <a-tag :color="item.type==1?'#87d068':'#108ee9'">
              {{ item.name }}
            </a-tag>
          </div>
        </template>

        <template slot="crmGroups" slot-scope="text,record">
          <div v-for="(item,index) in record.crmGroups" :key="index" style="margin-bottom:2px;">
            <a-tag>
              {{ item.name }}
            </a-tag>
          </div>
        </template>

        <span slot="action" slot-scope="text,record">
          <a @click="goInfo(record)">
            查看
          </a>
          <br/>
          <a @click="levelEdit(record)">修改等级</a>
          <br/>
          <a @click="lianEdit(record)">修改关系链</a>
          <br/>
          <a-popconfirm title="确定设为普通用户吗?" @confirm="() => cancelEdit(record)">
            <a>设为普通用户</a>
          </a-popconfirm>

        </span>
      </a-table>
    </div>

    <a-modal :title="integralTitle" :visible="integral_visible" :confirm-loading="integral_confirmLoading"
             @ok="integralOk"
             @cancel="integral_visible=false">
      <p>
        积分数量
        <a-input-number :step="1" :max="max_integral" placeholder="积分数量" v-model="integral"></a-input-number>
      </p>
    </a-modal>

    <a-modal title="设置分销员" :visible="set_hand_visible" :confirm-loading="set_hand_confirmLoading" @ok="levelEditOk"
             @cancel="handleCancel">
      <p>
        身份：
        <a-select size="small" style="margin:0 5px;" v-model="set_hand_level">
          <a-select-option v-for="(item3,index3) in levelList" :key="index3" :value="item3.level">
            {{ item3.name }}
          </a-select-option>
        </a-select>
      </p>
    </a-modal>
    <crm-tag-ref ref="modalLabels" :selectionType="'checkbox'" @ok="modalLabelOk"></crm-tag-ref>
    <tip-hand-set-ref ref="modalHandSets" :selectionType="'radio'" @ok="lianEditOk"></tip-hand-set-ref>
  </a-card>
</template>


<script>

import '@/assets/less/TableExpand.less'
import {mixinDevice} from '@/utils/mixin'
import {JeecgListMixin} from '@/mixins/MyJeecgListMixin'
import JDate from '@/components/jeecg/JDate.vue'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import TipHandSetRef from './modules/GospelHandSetRef.vue'
import CrmTagRef from '@/views/gospel/crm/modules/CrmTagRef'
import {putAction, getAction, postAction} from '@/api/manage'

export default {
  name: 'TipMemberList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    JDate, JDictSelectTag, CrmTagRef, TipHandSetRef
  },
  data() {
    return {
      set_hand_visible: false,
      set_hand_confirmLoading: false,
      set_hand_level: 1,
      select_id: null,
      max_integral: 0,
      integral_confirmLoading: false,
      integral_visible: false,
      integral_url: '',
      integralTitle: '加积分',
      uid: null,
      integral: 0,
      groupId: "",
      visible: false,
      isShow: false,
      description: 'tip_member管理页面',
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '昵称',
          align: "left",
          dataIndex: 'nickname'
        },
        {
          title: '手机号',
          align: "center",
          dataIndex: 'phone'
        },
        {
          title: '上级用户昵称',
          align: "left",
          dataIndex: 'parentNickname'
        },

        {
          title: '用户等级',
          align: "center",
          dataIndex: 'levelName'
        },
        {
          title: '下级数',
          align: "right",
          dataIndex: 'childNum'
        },

        {
          title: '累计佣金',
          align: "right",
          dataIndex: 'sumAmount'
        },
        {
          title: '等级更新时间',
          align: "center",
          dataIndex: 'updateLevelTime'
        },
        {
          title: '身份渠道',
          align: "center",
          dataIndex: 'channel',
          customRender: function (text) {
            return text == 1 ? '线上买礼包' : text == 3 ? '后台变更身份' : '任务升级'
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          fixed: "right",
          width: 147,
          scopedSlots: {customRender: 'action'}
        }
      ],
      url: {
        list: "/tipMember/list",
        edit: "/tipMember/edit",
        setHand: "/tipMember/setHand",
        cancelHand: "/tipMember/cancelHand",
        editLabels: "/tipMember/editLabels",
        editLian: "/tipMember/editLian",
        delete: "/tipMember/delete",
        deleteBatch: "/tipMember/deleteBatch",
        exportXlsUrl: "/tipMember/exportXls",
        importExcelUrl: "tipMember/importExcel",
      },
      dictOptions: {},
      usererstatus: 0,
      levelList: []
    }
  },
  created() {
    if (this.$route.params.record != null) {
      this.queryParam.groupId = this.$route.params.record.id
    }
    this.loadData()
    this.getLevels()


  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {

    onUpdateDateChange: function (value, dateString) {
      this.queryParam.updateLevelTime_begin = dateString[0]
      this.queryParam.updateLevelTime_end = dateString[1]
    },
    levelEdit(record) {
      this.select_id = record.id
      this.set_hand_visible = true
      if (record.level) {
        this.set_hand_level = record.level
      }
    },
    levelEditOk() {
      this.set_hand_confirmLoading = true
      putAction(this.url.setHand, {id: this.select_id, level: this.set_hand_level}).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.getAllMemberList()
        }
        this.loading = false
        this.handleCancel()
      })
    },
    cancelEdit(record) {
      putAction(this.url.cancelHand, {id: record.id}).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.getAllMemberList()
        }
      })
    },
    handleCancel() {
      this.set_hand_visible = false
      this.set_hand_confirmLoading = false
      this.set_hand_level = 1
    },
    getLevels() {
      var that = this
      getAction("/mallPlus/hmsHandConfig/list", {}).then((res) => {
        if (res.success) {
          that.levelList = res.result.records
        }
      })
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.queryParam.isHand = 1
      var params = this.getQueryParams()//查询条件
      this.loading = true
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.shopType = res.shopType
          this.orgCode = res.orgCode
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    labelEdit(record) {
      let self = this
      self.select_id = record.id
      self.$refs.modalLabels.visible = true
      self.$refs.modalLabels.checkedKeys = []
      self.$refs.modalLabels.checkedRows = []
      if (record.crmTags) {
        for (let i = 0; i < record.crmTags.length; i++) {
          self.$refs.modalLabels.checkedRows.push({id: record.crmTags[i].id})
          self.$refs.modalLabels.checkedKeys.push(record.crmTags[i].id)
        }
      }

      self.$refs.modalLabels.open()
    },
    modalLabelOk(rows, keys) {
      var that = this
      if (that.select_id) {
        putAction(that.url.editLabels, {id: that.select_id, tagList: rows}).then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.getAllMemberList()
            that.onClearSelected()
          } else {
            that.$message.warning(res.message)
          }
        }).finally(() => {
          that.loading = false
        })
      }

    },

    lianEdit(record) {
      let self = this
      self.select_id = record.id
      self.$refs.modalHandSets.visible = true
      self.$refs.modalHandSets.open(record.id)
    },
    lianEditOk(row, type) {
      var that = this
      if (that.select_id) {
        putAction(that.url.editLian, {id: that.select_id, otherId: row.id, type: type}).then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.getAllMemberList()
          } else {
            that.$message.warning(res.message)
          }
        })
      }
    },
    initDictConfig() {
    },
    goInfo(record) {
      this.$router.push({path: '/hand/user/memberinfo', query: {id: record.id}})
    },
    showModal() {
      this.visible = true
    },
    hideModal() {
      this.visible = false
    },
    confirm() {
      this.$confirm({
        title: 'Confirm',
        content: 'Bla bla ...',
        okText: '确认',
        cancelText: '取消',
      })
    },
    changerState(record) {
      let userstatus = 1
      if (record.status == 0) {
        userstatus = 1
      } else if (record.status == 1) {
        userstatus = 0
      }
      putAction(this.url.edit, {id: record.id, status: userstatus}).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.getAllMemberList()
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    getAllMemberList() {
      console.log("conming")
      var params = this.getQueryParams()//查询条件
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    getListByGid() {
      getAction(this.url.list, this.groupId).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    removeCompany(id) {
      putAction(this.url.edit, {id: record.id, isMember: 0}).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.getAllMemberList()
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    addIntegral(id) {
      this.uid = id
      this.max_integral = 100000000
      this.integralTitle = "加积分"
      this.integral_url = "/tipMember/addIntegral"
      this.integral = 0
      this.integral_visible = true
    },
    subIntegral(record) {
      this.uid = record.id
      this.max_integral = record.integral
      this.integralTitle = "减积分"
      this.integral_url = "/tipMember/subIntegral"
      this.integral = 0
      this.integral_visible = true
    },
    integralOk() {
      if (!this.integral) {
        this.$message.warning("输入积分必须大于0")
        return
      }
      this.integral_confirmLoading = true
      putAction(this.integral_url, {id: this.uid, integral: this.integral}).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.getAllMemberList()
          this.integral_visible = false
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.integral_confirmLoading = false
      })
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
